package bb.lanxing.activity.team;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.App;
import bb.lanxing.R;
import bb.lanxing.activity.base.BaseActivity;
import bb.lanxing.adapter.team.TeamListAdapter;
import bb.lanxing.model.database.Event;
import bb.lanxing.network.BiCiCallback;
import bb.lanxing.network.MyHttpClient;
import bb.lanxing.view.BikeHeader;
import okhttp3.Request;
import okhttp3.Response;

public class EventSearchActivity extends BaseActivity {
    public static final int LIMIT = 10;

    private EditText searchEdit;
    private View mSearchBtn;
    //    private PtrFrameLayout refreshView;
    private RecyclerView recyclerView;
    private TeamListAdapter mAdapter;

    private List<Event> mEventList = new ArrayList();
    private int mPage = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_event_search);
        bindView(getWindow().getDecorView());
    }

    private void bindView(View bindSource) {
        searchEdit = bindSource.findViewById(R.id.searchEdit);
//        searchEdit.setOnEditorActionListener((v, actionId, event) -> onEditFinish());
        mSearchBtn = bindSource.findViewById(R.id.searchBtn);
        mSearchBtn.setOnClickListener(view -> onSearchClick());

//        refreshView = bindSource.findViewById(R.id.refreshView);
        recyclerView = bindSource.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new TeamListAdapter();
        mAdapter.setOnItemClickListener(position -> {
            Event event = mEventList.get(position);
            if (event != null) {
                Intent intent = new Intent(getActivity(), TeamDetailActivity.class);
                intent.putExtra("event_id", event.getEventId());
                intent.putExtra("activity_partner", true);
                getActivity().startActivityForResult(intent, 76);
            }
        });
        recyclerView.setAdapter(mAdapter);
        BikeHeader bikeHeader = new BikeHeader(this);
//        refreshView.setHeaderView(bikeHeader);
//        refreshView.addPtrUIHandler(bikeHeader);
//        refreshView.setPtrHandler(new PtrDefaultHandler() {
//            @Override
//            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
//                return false;
//            }
//
//            @Override
//            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
//                loadData(searchEdit.getText().toString(), true);
//            }
//        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mEventList != null) {
            mEventList.clear();
            mEventList = null;
        }
    }

    public void refreshComplete() {
        runOnUiThread(() -> {
//            if (refreshView != null) {
//                refreshView.refreshComplete();
//            }
        });
    }

    private void onSearchClick() {
        loadData(searchEdit.getText().toString(), true);
    }

    boolean onEditFinish() {
        loadData(searchEdit.getText().toString(), true);
        return false;
    }

    public void loadData(String keyword, final boolean bPullDown) {
        if (bPullDown) {
            mPage = 0;
        }
        MyHttpClient.searchActivitys(new BiCiCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                super.onFailure(request, e);
                refreshComplete();
            }

            @Override
            public void onResponse(Response response) {
                try {
                    try {
                        super.onResponse(response);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } finally {
                    refreshComplete();
                }
            }

            @Override
            public void onResponseString(@NonNull String string) {
                ArrayList arrayList = new ArrayList();
                try {
                    JSONArray jSONArray = new JSONObject(string).getJSONArray("rows");
                    for (int i = 0; i < jSONArray.length(); i++) {
                        Event createByJson = Event.createByJson(jSONArray.getJSONObject(i));
                        createByJson.save();
                        arrayList.add(createByJson);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                updateDatas(arrayList, bPullDown);
            }
        }, keyword, mPage, 10);
    }

    public synchronized void updateDatas(final List<Event> eventList, final boolean needClean) {
        if (eventList != null) {
            mEventList = eventList;
            if (eventList.size() > 0) {
                runOnUiThread(() -> {
                    if (mAdapter != null) {
                        mAdapter.updateData(mEventList);
                    }
                });
                return;
            }
        }
        App.getContext().showMessage(R.string.event_search_toast_no_result);
    }
}